package com.zjf.carpark.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.zjf.carpark.entities.TOrder;
import com.zjf.carpark.service.TOrderService;
import com.zjf.carpark.utils.AlipayConfig;
import com.zjf.carpark.utils.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@CrossOrigin
@Controller
public class AlipayController {

    @Autowired
    private TOrderService tOrderService;
    // 获取配置文件的信息
    String app_id = AlipayConfig.app_id;
    String private_key = AlipayConfig.private_key;
    String notify_url = AlipayConfig.notify_url;
    String return_url = AlipayConfig.return_url;
    String url = AlipayConfig.url;
    String charset = AlipayConfig.charset;
    String format = AlipayConfig.format;
    String public_key = AlipayConfig.public_key;
    String signtype = AlipayConfig.signtype;


    // 支付宝沙箱支付
    @RequestMapping("/alipay")
    public void pay(String payMoney, String carNum, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println(payMoney);
        System.out.println(carNum);
        request.getSession().setAttribute("carNum", carNum);
        request.getSession().setAttribute("payMoney", payMoney);
        String subject = "停车费用订单"; // 订单名称
        String body = "这是一张停车缴费单"; // 商品描述

        String payOrder = UUID.randomUUID().toString(); // 生成订单号

        // 封装请求客户端
        AlipayClient client = new DefaultAlipayClient(url, app_id, private_key, format, charset, public_key, signtype);
        String path = request.getRequestURI();
        System.out.println(path);
        path = path.substring(0, path.lastIndexOf("/"));
        String resulturl = "http://localhost:8081" + return_url;
        // 支付请求
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(resulturl);
        alipayRequest.setNotifyUrl(notify_url);
        AlipayTradePayModel model = new AlipayTradePayModel();
        model.setProductCode("FAST_INSTANT_TRADE_PAY"); // 设置销售产品码
        model.setOutTradeNo(payOrder); // 设置订单号
        model.setSubject(subject); // 订单名称
        model.setTotalAmount(payMoney); // 支付总金额
        model.setBody(body); // 设置商品描述
        alipayRequest.setBizModel(model);

        String form = client.pageExecute(alipayRequest).getBody(); // 生成表单

        response.setContentType("text/html;charset=" + charset);
        response.getWriter().write(form); // 直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();


    }

    /**
     * 同步跳转
     *
     * @param request
     * @throws Exception
     */
    @RequestMapping("/returnUrl")
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ResponseData responseData = new ResponseData();
        System.out.println("支付结果");
        String carNum = (String) request.getSession().getAttribute("carNum");
        Double payMoney = Double.parseDouble((String) request.getSession().getAttribute("payMoney"));
        // 获取支付宝GET过来反馈信息（官方固定代码）
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            System.out.println("name:" + name);
            System.out.println("valueStr:" + valueStr);
            params.put(name, valueStr);
        }
        System.out.println("params:" + params);
        // 是否成功支付
        boolean signVerified = AlipaySignature.rsaCheckV1(params, public_key, charset, signtype); // 调用SDK验证签名

        // 返回界面
        if (signVerified) {
            // 修改数据库
            TOrder tOrder = new TOrder();
            tOrder.setCarnum(carNum);
            tOrder.setOrderprice(payMoney);
            tOrder.setOrderid(UUID.randomUUID().toString());
            tOrder.setCreatetime(new Date());
            tOrder.setRemark("这是一个费用清单");
            tOrderService.insert(tOrder);
            responseData.setMessage("前往支付成功页面");
            response.sendRedirect("http://localhost:8081/desk/paySuccess");
//
        } else {
            System.out.println("前往支付失败页面");
            response.sendRedirect("http://localhost:8081/desk/payfailed");
        }

    }

    /**
     * 支付宝服务器异步通知
     *
     * @param request
     * @throws Exception
     */
    @RequestMapping("/notifyUrl")
    public void notifyUrl(HttpServletRequest request) throws Exception {
        System.out.println("支付成功");
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, public_key, charset, signtype); // 调用SDK验证签名

        if (signVerified) { // 验证成功 更新订单信息
            System.out.println("异步通知成功");
            // 商户订单号
            String out_trade_no = request.getParameter("out_trade_no");
            // 交易状态
            String trade_status = request.getParameter("trade_status");
        } else {
            System.out.println("异步通知失败");
        }
    }
}
